<template>
    <div class="iconfont">
        <!-- grid layout -->

        <div class="row">
            <div class="col"></div>
            <div :data-error="error.account" :class="{addMsg: error.account !=''}" class="col-9">
                <div class="input-group mb-3">
                <div class="input-group-prepend">
                    <span class="input-group-text" id="basic-addon1">帐号</span>
                </div>
                <input type="text" class="form-control account-input" 
                v-model="login.account"
                placeholder="用户帐号" aria-label="Username" aria-describedby="basic-addon1">
                </div>
            </div>
            <div class="col"></div>
        </div>
        <div class="row">
            <div class="col"></div>
            <div :data-error="error.password" :class="{addMsg: error.password != ''}" class="col-9">
                <div class="input-group mb-3">
                <div class="input-group-prepend">
                    <span class="input-group-text" id="basic-addon1">密码</span>
                </div>
                <input type="password" class="form-control password-input" 
                v-model="login.password"
                placeholder="用户密码" aria-label="Username" aria-describedby="basic-addon1">
                </div>
            </div>
            <div class="col"></div>
        </div>
        <div v-if="verify" class="row">
            <div class="col"></div>
            <div :data-error="error.vericode" class="col-9" :class="{addMsg: error.vericode != ''}">
                <div class="input-group mb-3 " >
                <input type="text" class="form-control vericode " 
                v-model="login.vericode" :maxlength="4"
                placeholder="验证码" aria-label="verification-code" aria-describedby="img-verification">
                <div class="input-group-append">
                    <img :src="verify.dataURL" :alt="verify.code"
                        @click="freshCode"
                    >
                </div>
                </div>
            </div>
            <div class="col"></div>
        </div>
        <div class="row">
            <div class="col"></div>
            <div class="col-7" :data-error="error.btn" :class="{addMsg: error.btn != ''}">
                <button type="button" class="btn btn-primary btn-sm btn-block mb-3"
                @click="loginByAccount"
                >登录</button>
            </div>
            <div class="col"></div>
        </div>  
             

    </div>
</template>

<script>
import { loginByAccount } from "../../../api/login.js";
import cryptico from "cryptico-js";
import Verification from 'self-verification-code';
import { getPublickey } from "../../../api/homePage.js";
export default {
    data(){
        return {
            login:{
                account:"",
                password:"",
                vericode:""
            },
            error:{
                vericode:"",
                account:"",
                password:"",
                btn:""
            },
            
            verify: null
        };
    },
    methods:{
        checkVerificationCode( code ){
            if( this.verify.code === code ) return true;
            return false;
        },
        resetErrorMsg(){
            this.error.vericode="",
            this.error.account="",
            this.error.password="";
            this.error.btn = "";
        },
        async checkEmailFormula( val ){
            let C_v = (await import("../../../api/validate.js")).Validate;
            let v = new C_v();
            return v.checkEmail( val );
        },
        async checkPassWord( val ){
            let C_v = (await import("../../../api/validate.js")).Validate;
            let v = new C_v();
            return v.checkPasswordEmpty( val );
        },
         //刷新验证码
        freshCode(){
            let ver = Verification.CreateImgCode(); //生成验证码
            this.verify = ver;
        },
        async loginByAccount(){
            let that = this;
            this.resetErrorMsg();
            //错误处理
            let HttpError = (await import("../../../api/error.js")).HttpError;
            //校验
            if( !this.checkVerificationCode( this.login.vericode.toLowerCase() ) ){
                //检查验证码 
                // this.$(".password-input").focus();
                this.$(".vericode").focus();
                this.error.vericode = "验证码不正确，请重新输入！";
                return ;
            }

            if(  !(await this.checkEmailFormula(this.login.account)) ){
                //帐号检查
                this.$(".account-input").focus();
                this.error.account = "邮箱格式错误，请重新输入！";
                return ;
            }

            if(  !(await this.checkPassWord(this.login.password)) ){
                //帐号密码
                this.$(".password-input").focus();
                this.error.password = "密码格式错误，请重新输入！";
                return ;
            }

            //获取公钥
            await this.publickey();

            //加密 
            let pwd = this.encryptPassword(this.login.password);
            if(pwd.status = "success"){
                pwd = pwd.cipher;
            }else{
                return ;
            }

            loginByAccount( {
                account : this.login.account ,
                password:  pwd
            }).then(res=>{
                
                let token = res.data.data.token;
                localStorage.setItem("token", token); //本地保存
                this.$controlRouter.addRoutingUser(this);
                this.$router.replace('/func');
                // this.$router.push('/func');

            }).catch(err=>{
                
                this.error.btn = err.data.msg;
            });    
        },
        async publickey(){
            let that = this;
            let key = this.$store.getters.getPublicKey;
            if( key == "" ){
                //从服务端获取key值
                
                // getPublickey().then(function(res){
                //     that.$store.commit("setPublicKey", res.data.key);
                //     that = null;
                // }).catch(function(err){
                //     console.log(err);
                // });

                try{
                    let res = await getPublickey();
                    
                    if(res.code == 0 ){
                        that.$store.commit("setPublicKey", res.data.key);
                        that = null;
                        return ;
                    }
                }catch(err){
                    console.log(err);
                }
            }
            
            
        },
        encryptPassword(val){
            let enkey = cryptico.encrypt(val , this.$store.getters.getPublicKey)
            return enkey;
        }
    },
    mounted(){
        let ver = Verification.CreateImgCode(); //生成验证码
        this.verify = ver;
        
    }
}
</script>

<style lang="scss">

.addMsg{
    display: flex;
    flex-direction: column;
}
.addMsg::after{
    content: "\e605"" "attr(data-error);
    text-align: left;
    padding: .375rem .75rem .375rem 0;
    margin-top: -.9rem;
    color: red;
}
</style>